<template>
  <div>
    <treeNodeCard
      v-if="props.type === 'view'"
      @handle-click="handleClick"
      :state="state"
      @handle-add-children="handleClickAddChildren"
    />
    <basicsEditCard
      v-if="props.type === 'edit'"
      @handle-add-icon="handleAddIcon"
      @handle-remove-icon="handleRemoveIcon"
      @handleEditNode="handleEditNode"
      :state="state"
    />
  </div>
</template>

<script setup lang="ts">
import { inject, onMounted, reactive } from "vue";
import treeNodeCard from "./basicsCard.vue";
import basicsEditCard from "./basicsEditCard.vue";

// 定义 NodeData 和 Node 类型
interface NodeData {
  index: number;
  layer: number;
  departmentName: string;
  avatar?: string;
  headcount?: number;
  establishmentCount?: number;
  waitIn?: number;
  duringOut?: number;
  money?: number;
  deptLevel: string;
  userName: string;
  position: string;
  overEstablishment: string;
  isEditShow: string;
  pCode: string;
  parentdepartmentName: string;
  deptLevelName: string;
  departmentCode: string;
  isHaveChildren: boolean;
  code: string;
  portionManageName: string;
  manageName: string;
  children: NodeData[];
}

interface Node {
  data: NodeData;
  id: number;
  on: (event: string, callback: (args) => void) => void;
}

// 注入 getNode 函数
const getNode = inject<() => Node>("getNode");

// 定义事件
const emits = defineEmits(["handleClick", "handleAddIcon", "handleRemoveIcon", "handleEditNode", "handleClickAddChildren"]);

// 定义组件属性
const props = defineProps({
  type: {
    type: String,
    default: "view"
  }
});

// 定义响应式状态
const state = reactive<NodeData>({
  id: 0,
  index: 0,
  departmentName: "",
  layer: 0,
  avatar: "",
  headcount: 0,
  establishmentCount: 0,
  waitIn: 0,
  duringOut: 0,
  money: 0,
  deptLevel: "",
  userName: "",
  position: "",
  overEstablishment: "",
  isEditShow: "",
  pCode: "",
  parentdepartmentName: "",
  deptLevelName: "",
  departmentCode: "",
  isHaveChildren: false,
  code: "",
  children: []
});

// 组件挂载时初始化状态
onMounted(() => {
  init();
});

// 初始化状态
const init = () => {
  const node = getNode?.();

  if (node) {
    updateStateFromNode(node);

    node.on("change:data", ({ current }) => {
      state.index = current.index;
      state.layer = current.layer;
    });
  }
};

// 更新状态函数
const updateStateFromNode = (node: Node) => {
  Object.assign(state, node.data, { id: node.id });
};

// 事件处理函数
const handleClick = data => emits("handleClick", data);
const handleClickAddChildren = data => emits("handleClickAddChildren", data);
const handleRemoveIcon = data => emits("handleRemoveIcon", data);
const handleAddIcon = data => emits("handleAddIcon", data);
const handleEditNode = data => emits("handleEditNode", data);
</script>
